package login.Utils;

import org.apache.commons.dbcp2.BasicDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    private JDBCUtils(){

    }
    //连接池
    private static BasicDataSource bs;

    //初始化连接池
    static {
        Properties properties = new Properties();
        InputStream rs = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(rs);
            /*创建一个连接池*/
            bs = new BasicDataSource();
            //设置连接池参数
            /*必备的四个参数*/
            bs.setDriverClassName(properties.getProperty("driver"));
            bs.setUrl(properties.getProperty("url"));
            bs.setUsername(properties.getProperty("user"));
            bs.setPassword(properties.getProperty("password"));

            /*设置可选参数*/
            bs.setInitialSize(12);
            bs.setMaxTotal(12);
            bs.setMaxIdle(2);
            bs.setMinIdle(1);
            bs.setMaxWaitMillis(30000);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(){
        Connection conn=null;
        try {
            conn = bs.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    //
    public static DataSource getDataSource(){
        return bs;
    }


}
